import { router } from '@/router'
import { isWithoutToken } from './helpers'
import { getToken, removeToken } from '@/utils/token'
import { checkStatus } from './checkStatus';

export function setupInterceptor(service: any) {
  service.interceptors.request.use(
    async (config: any) => {
      // 防止缓存，给get请求加上时间戳
      if (config.method === 'get') {
        config.params = { ...config.params, t: new Date().getTime() }
      }

      // 处理不需要token的请求
    if (isWithoutToken(config)) {
          return config
    }

      const token = getToken()
      if (token) {
        // if (!config.headers.Authorization) config.headers.Authorization = 'Bearer ' + token
        config.withCredentials = true;
        return config;
      }
      /**
       * * 未登录或者token过期的情况下
       * * 跳转登录页重新登录，携带当前路由及参数，登录成功会回到原来的页面
       */
      const { currentRoute } = router
      router.replace({
        path: '/login',
        query: { ...currentRoute.query, redirect: currentRoute.path },
      })
      return Promise.reject({ code: '-1', message: '未登录' })
    },
    (error: any) => Promise.reject(error)
  )

  service.interceptors.response.use(
    (response: any) => response?.data,
    (error: any) => {
      console.log('error:::', error);
      let { code, message } = error.response?.data;

      checkStatus(code, message);
      return Promise.reject({ code, message });
    }
  )
}
